<?php

namespace app\sys\command;

use think\Db;
use think\console\Command;
use think\console\Input;
use think\console\Output;

// 定时任务 - 自动收货 发货10天后自动收货 每半个小时执行 （收货分2种 一种10天自动收货并默认好评 二种主动确认收货 两种方式都将订单改交易成功状态 不可退款）
class AutoReceive extends Command
{
    protected function configure()
    {
        $this->setName('auto_receive')->setDescription('自动收货 发货10天后自动收货');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job start================');

        $this->job();

        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job end================');
    }

    private function job()
    {
        $time = time();
        $bt = $time - 86400 * 10 - 3600;
        $et = $time - 86400 * 10 - 1800;
        $wx_service = new \wx\WeixinService();
        $wxgzh_service = new \wx\WxgzhService();
        // 发货10天后 买家自动收货
        $order_list = Db::name('order')->where(['status' => 2, 'send_time' => [['gte', $bt], ['lte', $et]]])->select();
        Db::name('order')->where(['status' => 2, 'send_time' => [['gte', $bt], ['lte', $et]]])->update(['status' => 12, 'receive_time' => $time]);

        // 买家自动收货后将钱写进供应商余额 并写财务明细记录
        financeDetail($order_list);

        // 申请售后 买家发货 卖家5天(提前2天)收到提醒收货通知
        $refund_bt = $time - 86400 * 5 - 3600;
        $refund_et = $time - 86400 * 5 - 1800;
        $seller_order_list = Db::name('order')->where(['status' => 4, 'buyer_send_time' => [['gte', $refund_bt], ['lte', $refund_et]]])->select();
        foreach ($seller_order_list as $key => $order_info) {
            $product = Db::name('product')->field('name')->find($order_info['product'][0]['product_id']);
            $return_money = round($order_info['apply_refund_money'] - $order_info['total_postage'], 2);
            $admin_info = Db::name('admin')->where('id', $order['admin_id'])->find();
            if ($admin_info['gzh_openid']) {
                // 发送公众号模板消息（给供应商）
                $data = [
                    'first' => ['value' => '买家已发货5天了，请及时处理退货！'],
                    'keyword1' => ['value' => strval($order_info['id'])],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => $return_money.'元'],
                    'keyword4' => ['value' => '至'.date('Y-m-d H:i:s', $order_info['buyer_send_time'] + 86400 * 7).'为止'],
                    'remark' => ['value' => '买家发货后7天将自动收货，如货物有问题请在后台驳回申请'],
                ];
                $wxgzh_service->sendTemplateMsg($admin_info['gzh_openid'], 'zkrL0pm3VLRB6lHU4zvMl7mU1C0gLfflF5BLdmAMISE', $data);
            }
        }

        // 申请售后 买家发货 卖家7天自动收货 退款不写财务明细（财务明细只有收入）
        $refund_bt = $time - 86400 * 7 - 3600;
        $refund_et = $time - 86400 * 7 - 1800;
        $seller_order_list = Db::name('order')->where(['status' => 4, 'buyer_send_time' => [['gte', $refund_bt], ['lte', $refund_et]]])->select();
        Db::name('order')->where(['status' => 4, 'buyer_send_time' => [['gte', $refund_bt], ['lte', $refund_et]]])->update(['status' => 11, 'seller_receive_time' => $time]);
        // 订单发货了 先同意退款 然后买家发货 卖家收货后 退款减去运费
        foreach ($seller_order_list as $key => $order_info) {
            // 因为第一版是单产品单地址 所以total_postage即是总运费
            $result = $wx_service->payOrderRefund($order_info['transaction_id'], $order_info['id'], round($order_info['total_fee'], 2), round($order_info['total_fee'], 2));
            if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
                Db::name('order')->where('id', $result['out_trade_no'])->update(['status' => 15, 'seller_receive_time' => time(), 'refund_time' => time()]);
                $return_money = round($order_info['total_fee'] - $order_info['total_postage'], 2);
                $product = Db::name('product')->field('name')->find($order_info['product'][0]['product_id']);
                $db_ui = Db::name('user')->find($order_info['buyer']);
                if ($db_ui['gzh_openid']) {
                    //发送模板消息 公众号 退货成功（给买家）
                    $data = [
                        'first' => ['value' => '您的订单已经退货成功了'],
                        'keyword1' => ['value' => strval($order_info['id'])],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => $return_money.'元'],
                        'keyword4' => ['value' => date('Y-m-d H:i:s', time())],
                        'remark' => ['value' => '卖家已收到货品，退款已退回微信零钱,感谢你的使用。'],
                    ];
                    $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'zkrL0pm3VLRB6lHU4zvMl7mU1C0gLfflF5BLdmAMISE', $data, 'pages/index/welcome');
                } elseif ($order_info['openid']) {
                    //发送模板消息 小程序 退货成功（给买家）
                    $tData = [
                        'keyword1' => ['value' => strval($order_info['id'])],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => $return_money.'元'],
                        'keyword4' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
                        'keyword5' => ['value' => '退货成功'],
                        'keyword6' => ['value' => '卖家已收到货品，退款已退回微信零钱,感谢你的使用。'],
                    ];
                    $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'OM3HX_vPs5ueiqgPFP1YSKLfNWp683-aNCfK582-Oh4', 'pages/index/welcome', $tData);
                }
                // 减少待结算金额
                notSettlemetnChange($order_info, false);
            }
        }

        // 申请退款 订单未发货 申请后3天卖家未处理 自动退款给买家
        $refund_bt = $time - 86400 * 3 - 3600;
        $refund_et = $time - 86400 * 3 - 1800;
        $refund_order_list = Db::name('order')->where(['status' => 5, 'apply_time' => [['gte', $refund_bt], ['lte', $refund_et]]])->select();
        Db::name('order')->where(['status' => 5, 'apply_time' => [['gte', $refund_bt], ['lte', $refund_et]]])->update(['status' => 11, 'confirm_refund_time' => $time]);

        foreach ($refund_order_list as $key => $order_info) {
            $result = $wx_service->payOrderRefund($order_info['transaction_id'], $order_info['id'], round($order_info['total_fee'], 2), round($order_info['total_fee'], 2));
            if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
                Db::name('order')->where('id', $result['out_trade_no'])->update(['status' => 11, 'refund_time' => time()]);
                $product = Db::name('product')->field('name')->find($order_info['product'][0]['product_id']);
                $db_ui = Db::name('user')->find($order_info['buyer']);
                if ($db_ui['gzh_openid']) {
                    //发送模板消息 公众号 退货成功（给买家）
                    $data = [
                        'first' => ['value' => '您的订单已经退款成功了'],
                        'keyword1' => ['value' => strval(round($order_info['total_fee'], 2)).'元'],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => strval($order_info['id'])],
                        'keyword4' => ['value' => strval($order_info['reason'])],
                        'remark' => ['value' => '已退回微信零钱,感谢你的使用。'],
                    ];
                    $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'RlLrUWzjsVqcRd5DxTDhZ1mti7m97ZFxtKgsNUX_bNI', $data, 'pages/index/welcome');
                } elseif ($order_info['openid']) {
                    // 发送模板消息
                    $tData = [
                        'keyword1' => ['value' => $order_info['id']],
                        'keyword2' => ['value' => strval($product['name'])],
                        'keyword3' => ['value' => $order_info['total_fee'].'元'],
                        'keyword4' => ['value' => date('Y-m-d H:i:s', time())],
                        'keyword5' => ['value' => '已退回微信零钱,感谢你的使用。'],
                    ];
                    $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], '6hSfXpoutPciTAJYli9XI05Lqzg9wH7n4GjlD2oV5E8', 'pages/index/welcome', $tData);
                }
                // 减少待结算金额
                notSettlemetnChange($order_info, false);
            }
        }

        // 卖家同意退货之后 7天买家未发货 订单结束
        $refund_bt = $time - 86400 * 7 - 3600;
        $refund_et = $time - 86400 * 7 - 1800;
        $refund_order_list = Db::name('order')->where(['status' => 13, 'confirm_return_goods_time' => [['gte', $refund_bt], ['lte', $refund_et]]])->select();
        Db::name('order')->where(['status' => 13, 'apply_time' => [['gte', $refund_bt], ['lte', $refund_et]]])->update(['status' => 12, 'over_time' => $time, 'receive_time' => $time]);

        // 退货失败 直接打给供应商 并写财务明细记录
        financeDetail($refund_order_list);
        foreach ($refund_order_list as $key => $order_info) {
            $product = Db::name('product')->field('name')->find($order_info['product'][0]['product_id']);
            $return_money = round($order_info['total_fee'] - $order_info['total_postage'], 2);
            $db_ui = Db::name('user')->find($order_info['buyer']);
            if ($db_ui['gzh_openid']) {
                //发送模板消息 公众号 退货失败（给买家）
                $data = [
                    'first' => ['value' => '您的订单申请退货失败'],
                    'keyword1' => ['value' => strval($order_info['id'])],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => strval(intval($order_info['total_number']))],
                    'keyword4' => ['value' => strval($order_info['total_money']).'元'],
                    'remark' => ['value' => '买家未在7天内发货给卖家，交易结束'],
                ];
                $wxgzh_service->sendTemplateMsg($db_ui['gzh_openid'], 'YT1kCxUnMDp91qWS21jYqsi_XZFNUA9CQirveh9NL1A', $data, 'pages/index/welcome');
            } elseif ($order_info['openid']) {
                //发送模板消息
                $tData = [
                    'keyword1' => ['value' => $order_info['id']],
                    'keyword2' => ['value' => strval($product['name'])],
                    'keyword3' => ['value' => $return_money.'元'],
                    'keyword4' => ['value' => date('Y-m-d H:i:s', $order_info['apply_time'])],
                    'keyword5' => ['value' => '退货失败'],
                    'keyword6' => ['value' => '买家未在7天内发货给卖家，交易结束'],
                ];
                $wx_service->sendTemplateMsg($order_info['openid'], $order_info['prepay_id'], 'OM3HX_vPs5ueiqgPFP1YSKLfNWp683-aNCfK582-Oh4', 'pages/index/welcome', $tData);
            }
            // 这里不减少待结算金额 （红包时打开减少）
        }

        // 自动默认好评
        $order_list = Db::name('order')->where(['status' => 12, 'send_time' => [['gte', $bt], ['lte', $et]]])->select();
        foreach ($order_list as $key => $value) {
            defaultGoodEvaluate($value);
        }
    }
}
